<?php

namespace app\index\controller;

use app\common\controller\Frontend;

use app\common\model\InviteLog;
use think\Db;
use fast\Random;
use think\Config;
use think\Validate;
use app\common\library\Sms;
use app\common\model\User as UserModel;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;


class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        return $this->view->fetch();
    }

    public function invite()
    {
        $invite = $this->request->request('code');
        $postion = $this->request->request('postion');
        $this->view->assign('invite', $invite);
        $this->view->assign('postion', $postion);
        return $this->view->fetch();
    }


    public function storeinvite(){
        $invite = $this->request->request('code');
        $postion = $this->request->request('postion',3);
        $this->view->assign('invite', $invite);
        $this->view->assign('postion', $postion);
        return $this->view->fetch();
    }


    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha  验证码
     */
    public function register()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $invitecode = $this->request->post('invite');
        $postion = $this->request->post('postion');

        if (!$mobile || !$captcha) {
            $this->error('请填写完整信息');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('号码格式错误');
        }
        $ret = Sms::check($mobile, $captcha, 'register');
        if (!$ret) {
            $this->error('验证码错误');
        }
        $user = \app\common\model\User::where(['postion'=>$postion,'mobile'=>$mobile])->find();
        if ($user) {
            $this->error('该手机号已被注册');
        }

        $avatar   = Db::name('config')->where(['name' => 'default_avatar'])->value('value');
        // 用户邀请二维码（微信）
        $invite_code = rand(1111, 9999);
        $intr=\app\admin\model\User::where(['invite_code'=>$invite_code])->find();
        if($intr){
            $postion=$intr->postion;
        }
        $invite = $this->build($invite_code);
        $extend = [
            'avatar'        => $avatar,
            'invite_code'          =>$invite_code,
            'invite_url'     => $invite,
             'postion'=>$postion,
        ];

        $ret = $this->auth->register($mobile, '123456',$mobile, $extend);
        if ($ret) {
            //绑定上级
            $Invitee = $this->invitecode($invitecode);
            if($Invitee){
                $data = [
                    'Invitee'    => $Invitee['Invitee'],
                    'Invitees'   => $this->auth->id,
                    'createtime' => time()
                ];
                Invitelog::create($data);
            }
            $this->success('注册成功');
        } else {
            $this->error($this->auth->getError());
            $this->error('注册失败,请稍后再试');
        }
    }

    /**
     * 邀请封装
     *
     */
    public function invitecode($invitecode)
    {
        if ($invitecode) {
            $userinfo = \app\common\model\User::where('invite_code', $invitecode)->find();
            if ($userinfo) {
                return ['Invitee' => $userinfo['id']];
            } else {
                return false;
            }
        }
    }

    // 生成二维码 (普通二维码)
    public function build($code)
    {
        $config = get_addon_config('qrcode');
        $params = [];
//        $params['text'] = $text;
        $params['text'] = request()->domain() . '/index/index/invite/?channelCode=10001&code=' . $code;
        $qrCode = \addons\qrcode\library\Service::qrcode($params);
        $returnPath = '';
        // 写入到文件
        if ($config['writefile']) {
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/' . date('Ymd') . '/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
                $key = md5(implode('', $params)) . '.' . $config['format'];
                return '/uploads/qrcode/' . date('Ymd') . '/' . $key;
            }
        }
        return ['path' => $returnPath];

    }


}
